﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Vit.Common;

namespace Vit.Common
{
    public class PagerList<T> : List<T>, IPager
    {
        public PagerList(IQueryable<T> query, int pageIndex, int pageSize)
        {
            int totalItemCount = query.Count();
            if (pageIndex < 1)
                pageIndex = 1;

            if (pageIndex > 1 && totalItemCount <= pageSize)
                pageIndex = 1;

            query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            AddRange(query.ToList());

            PagingInfo = new PagingInfo(pageIndex, pageSize, totalItemCount);
        }

        public PagerList(CachableQuery<T> cachableQuery, int pageIndex, int pageSize)
        {
            int totalItemCount = cachableQuery.Query.Count();
            if (pageIndex < 1)
                pageIndex = 1;

            if (pageIndex > 1 && totalItemCount <= pageSize)
                pageIndex = 1;

            cachableQuery.Query = cachableQuery.Query.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            AddRange(cachableQuery.Query.ToList());

            PagingInfo = new PagingInfo(pageIndex, pageSize, totalItemCount);
        }

        public PagingInfo PagingInfo { get; set; }
    }
}
